#include <buola/gui.h>

#include <buola/gui/ctoolkit.h>
#include <buola/gui/cclipboard.h>
#include <buola/image/cimage.h>

#include <buola/gui/dnd/cdrag.h>
#include <buola/gui/dnd/cdragsource.h>
#include <buola/gui/dnd/cdndwindow.h>

namespace buola { namespace gui {

CDrag::CDrag(CDragSource *pSource,const img::CPicture &pImage)
{
    mSource=pSource;
    mSourceWin=pSource->mDragWindow;
    mImage=pImage;

    mLastPointer=CPointer::STOCK_NOSTOCK;
    mHotSpot={0,0};

    mDecoration=nullptr;
    mImpl=get_toolkit()->GetDragImpl(this);
}

void CDrag::SetImage(const img::CPicture &pImage)
{
    mImage=pImage;
}

void CDrag::SetHotSpot(const CPoint_d &pPoint)
{
    mHotSpot=pPoint;
}

void CDrag::Drag()
{
    mSource->OnDragDrag(this,get_toolkit()->GetClipboard(CClipboard::DRAGNDROP));

    if(!get_toolkit()->GetClipboard(CClipboard::DRAGNDROP)->IsOwned())
    {
        msg_warn() << "Dragging but selection not owned\n";
        return;
    }

    mImpl->DragStart();
}

void CDrag::Move(const CPoint_d &pPoint)
{
    if(!mDecoration)
    {
        mDecoration=new CDndWindow;
        mDecoration->SetImage(mImage);
        mDecoration->Move(CPoint_d(pPoint-mHotSpot));
        mDecoration->Show();
    }
    else
    {
        mDecoration->Move(pPoint-mHotSpot);
    }

    mLastPoint=pPoint;
}

void CDrag::Finish()
{
    mDecoration->Unmap();
    mDecoration=nullptr;
}

void CDrag::Discard()
{

}

void CDrag::Drop()
{
}

void CDrag::SetStatus(EDNDStatus pStatus)
{
    CPointer::EStock lNewPointer=(pStatus==DND_UNKNOWN||
                pStatus==DND_ACCEPTED||pStatus==DND_FINISHED)?
                     CPointer::STOCK_DEFAULT:CPointer::STOCK_NO;

    if(lNewPointer==mLastPointer) return;

    mSourceWin->SetPointer(lNewPointer);
    mLastPointer=lNewPointer;
}

/*namespace gui*/ } /*namespace buola*/ }
